package com.blog.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.blog.pojo.Chat;
import com.blog.service.impl.ChatServiceImpl;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 2018年5月18日16:11:48
 */
@Component
@ServerEndpoint("/websocket/{uuid}")
public class WebSocketController {

    private static ChatServiceImpl chatService;
    @Autowired
    public void setChatServiceImpl(ChatServiceImpl chatService){
        WebSocketController.chatService= chatService;
    }

    /**concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。*/
    private static CopyOnWriteArraySet<Session> webSocketSet = new CopyOnWriteArraySet<Session>();
    /**
     * 会话
     */
    private Session session;

    /**
     * 建立连接
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("uuid") String uuid , Session session) {
        System.out.println(session.getId()+"建立了连接");
        webSocketSet.add(session);
}

    /**
     * 连接关闭
     */
    @OnClose
    public void onClose(Session session){
        webSocketSet.remove(session);
        System.out.println(session.getId()+"关闭了连接");
        System.out.println("在线人数"+webSocketSet.size());
    }

    /**
     * 收到客户端的消息
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) throws JSONException, IOException {
        int maxSize = 5 * 1024; // 5K
        session.setMaxTextMessageBufferSize(maxSize);
        JSONObject jsonObject = new JSONObject(message);
        String chatHeadPhoto = (String) jsonObject.get("chatHeadPhoto");
        String chatName = (String) jsonObject.get("chatName");
        String chatContent = (String) jsonObject.get("chatContent");
        String uuid = (String) jsonObject.get("uuid");
        Date time = new Date();
/*        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:MM-ss");
        String format = sdf.format(time);*/
        Chat chat = new Chat(0, chatName, chatHeadPhoto, chatContent, time,uuid);
        chatService.addChat(chat);
        System.out.println("收到客户端的消息");

        String chatsJson = JSON.toJSONString(chat,SerializerFeature.QuoteFieldNames,SerializerFeature.PrettyFormat);
        sendMessage(chatsJson);
        System.out.println(chatsJson);
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        for (Session session : webSocketSet){
            session.getAsyncRemote().sendText(message);
        }
    }
}